package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.constant.RegionInfoConstant;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.query.WudianQueryRequest;
import com.sto.stoapp.http.response.query.WudianQueryResponse;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint({ "HandlerLeak", "NewApi" })
public class SalesWdcpQueryActivity extends StoHomeActivity implements
		RegionInfoConstant {

	private StoHhmEditText branch, district, keyword;
	private StoHhmEditText province, city;
	private final int PROVINCE_RESULT = 0xfe;
	private final int CITY_RESULT = 0xfd;
	private final int DISTRICT_RESULT = 0xfc;
	private final int BRANCH_RESULT = 0xfb;
	private Boolean isBranch = false;

	private String branchCode = "";

	private List<EditText> edit = new ArrayList<EditText>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_wdcp_query);
		Bundle extras = getIntent().getExtras();
		this.setTitleBottom(R.string.wdcpcx_title, extras.getString("busiType"));

		initWidget();
		initListener();
	}

	private void initWidget() {
		branch = ((StoHhmEditText) this.findViewById(R.id.branch_text));
		province = ((StoHhmEditText) this.findViewById(R.id.province_text));
		city = ((StoHhmEditText) this.findViewById(R.id.city_text));
		district = ((StoHhmEditText) this.findViewById(R.id.district_text));
		keyword = ((StoHhmEditText) this.findViewById(R.id.keyword_text));
		edit.add(branch);
		branch.setInputType(InputType.TYPE_CLASS_TEXT);
		province.setInputType(InputType.TYPE_CLASS_TEXT);
		city.setInputType(InputType.TYPE_CLASS_TEXT);
		district.setInputType(InputType.TYPE_CLASS_TEXT);
		keyword.setInputType(InputType.TYPE_CLASS_TEXT);
	}

	// private boolean isBackKey = false;
	private void initListener() {

		branch.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {

				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				SelectBranch();

			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SelectBranch();
			}
		});

		province.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				branch.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				SelectProvince();

			}
		});

		city.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				province.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (CheckItem(CITY_RESULT)) {
					SelectCity();
				}
			}
		});

		district.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				city.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (CheckItem(DISTRICT_RESULT)) {
					SelectDistrict();
				}
			}
		});

		keyword.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				if (district.isEnabled()) {
					district.requestFocus();
				} else {
					branch.requestFocus();
				}

			}

			@Override
			public void onEditClickListener(View v) {
				QueryEvent();

			}
		});

		for (EditText editListener : edit) {

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					if (branch.getText().toString().isEmpty()) {
						isBranch = false;
						branchCode = "";
						province.setText("");
						city.setText("");
						district.setText("");
						province.setEnabled(true);
						city.setEnabled(true);
						district.setEnabled(true);
					} else {
						isBranch = true;
						province.setText("");
						city.setText("");
						district.setText("");
						province.setEnabled(false);
						city.setEnabled(false);
						district.setEnabled(false);
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PROVINCE_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				province.setText(courierEntity.getSelectCode());
				province.setSelection(province.length());
				city.setText("");
				district.setText("");
				city.requestFocus();

			}
		} else if (requestCode == CITY_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			city.setText(courierEntity.getSelectCode());
			city.setSelection(city.length());
			district.setText("");
			district.requestFocus();

		} else if (requestCode == DISTRICT_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			district.setText(courierEntity.getSelectCode());
			district.setSelection(district.length());
			keyword.requestFocus();
		} else if (requestCode == BRANCH_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			branchCode = courierEntity.getSelectCode();// courierEntity.getSelectCode();
			branch.setText(courierEntity.getSelectName());
			keyword.requestFocus();
		} else if (requestCode == BRANCH_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			branch.setText("");
			Helper.showSoundToast(this, "未检索到数据,请到业务设置中更新数据", false);
		} else if (resultCode == RESULT_FIRST_USER) {
			Helper.showSoundToast(this, "未检索到数据,请到业务设置中更新数据", false);
		}

	}

	/**
	 * 选择网点
	 */
	private void SelectBranch() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (branch.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ONLY_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ branch.getText().toString() + "%" });
			}
			tableParcel.setSelectCode("site_code_number");
			tableParcel.setSelectName("site_code_name");
			tableParcel.setProperty(null);

			Intent intent = new Intent(SalesWdcpQueryActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, BRANCH_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectProvince", e.getMessage());
		}
	}

	/**
	 * 选择省份
	 */
	private void SelectProvince() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (province.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_REGION_PROVINCE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_PROVINCE_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ province.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(NAME);
			tableParcel.setSelectName(null);
			tableParcel.setProperty(null);
			province.setText("");

			Intent intent = new Intent(SalesWdcpQueryActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, PROVINCE_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectProvince", e.getMessage());
		}
	}

	/**
	 * 选择城市
	 */
	private void SelectCity() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (city.getText().length() == 0) {
				tableParcel.setSelectSql(SqlSelectTableManager.SQL_CITY_ALL);
				tableParcel.setSelectField(new String[] { province.getText()
						.toString() });
			} else {
				tableParcel.setSelectSql(SqlSelectTableManager.SQL_CITY_LIKE);
				tableParcel.setSelectField(new String[] {
						province.getText().toString(),
						"%" + city.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(NAME);
			tableParcel.setSelectName(null);
			tableParcel.setProperty(null);
			city.setText("");
			Intent intent = new Intent(SalesWdcpQueryActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, CITY_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectCity", e.getMessage());
		}
	}

	/**
	 * 选择地区
	 */
	private void SelectDistrict() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (district.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_DISTRICT_ALL);
				tableParcel.setSelectField(new String[] { city.getText()
						.toString() });
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_DISTRICT_LIKE);
				tableParcel.setSelectField(new String[] {
						city.getText().toString(),
						"%" + district.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(NAME);
			tableParcel.setSelectName(null);
			tableParcel.setProperty(null);
			district.setText("");
			Intent intent = new Intent(SalesWdcpQueryActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, DISTRICT_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectDistrict", e.getMessage());
		}
	}

	private boolean CheckItem(int item) {
		boolean ret = true;
		if (isNetworkConnected() == false) {
			Helper.showSoundToast(this, "请进行联网后再次查询", false);
			return false;
		}
		if (!isBranch) {
			if (item == PROVINCE_RESULT) {

			}
			if (item == CITY_RESULT) {
				if (province.getText().length() == 0) {
					Helper.showSoundToast(this, "请输入省份", false);
					city.setText("");
					province.requestFocus();
					ret = false;
				}
				return ret;
			}
			if (item == DISTRICT_RESULT) {
				if (province.getText().length() == 0) {

					Helper.showSoundToast(this, "请输入省份", false);
					district.setText("");
					province.requestFocus();
					return false;
				}
				if (city.getText().length() == 0) {

					Helper.showSoundToast(this, "请输入城市", false);
					district.setText("");
					city.requestFocus();
					return false;
				}

				return true;
			}
		} else {
			if (branchCode.isEmpty()) {
				Helper.showSoundToast(this, "网点编号不存在", false);

				return false;
			}
			if (!branchCode.equals(branch.getText().toString())) {
				Helper.showSoundToast(this, "请选择正确的网点", false);
				branch.requestFocus();
				return false;
			}
		}
		return ret;
	}

	public boolean isNetworkConnected() {
		@SuppressWarnings("static-access")
		ConnectivityManager mConnectivityManager = (ConnectivityManager) this
				.getSystemService(this.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}

		return false;
	}

	private void QueryEvent() {
		if (CheckItem(DISTRICT_RESULT)) {
			new QueryThread(
					this,
					new WudianQueryRequest(this, branchCode, province.getText()
							.toString(), city.getText().toString(), district
							.getText().toString(), keyword.getText().toString()))
					.start();

		}
	}

	private void exitShuRuFa() {
		InputMethodManager imm = (InputMethodManager) branch.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		imm.hideSoftInputFromWindow(branch.getWindowToken(), 0);
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		// exitShuRuFa();
		showNotice();
		// super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		edit.clear();
		// handler.removeMessages(WdcpQueryThread.WDCPQUERY_REQUEST_CODE);
		super.onDestroy();
	}

	class QueryThread extends BaseThread {

		WudianQueryRequest request;
		Context context;

		public QueryThread(Context context, WudianQueryRequest request) {
			super(context);
			this.request = request;
			this.context = context;

			showDialog();
		}

		@Override
		public void run() {
			super.run();

			HttpManager mgr = new HttpManager();
			String str = mgr.doPostClient(request.buildToRequestString(),
					StoFilePreference.getInstance(context).getServerIp()
							+ URLActions.DELIVERY_SCOPE_ACTION);

			Gson gs = new Gson();
			WudianQueryResponse response = null;
			try {
				response = gs.fromJson(str,
						new TypeToken<WudianQueryResponse>() {
						}.getType());
			} catch (JsonSyntaxException e) {
				e.printStackTrace();

				ExceptionLog.writeLog("SalesWdcpQueryActivity", "无点超派解析失败:"
						+ str);

			}
			if (response == null) {
				showMgs("查询结果解析失败");
			} else {
				if (response.deliverQueryResult == null) {
					showMgs("没查到符号条件的信息");
				} else {
					showMgs(response.deliverQueryResult);
				}
			}

			cancelDialog();

		}

		private void showMgs(final String text) {
			runOnUiThread(new Runnable() {
				public void run() {
					Helper.showToast(context, text);
				}
			});
		}
	}

}
